package com.gxa.controller;

import com.gxa.common.R;
import com.gxa.pojo.Document;

import com.gxa.service.DocumentService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 张剑宇
 * Date: 2021/12/03 14:03
 * Description:
 * Version: V1.0
 */


@Controller
@Api(value = "数据test",tags = "附件接口API(跟单,工单)-张剑宇")

@RequestMapping("/document")
public class DocumentController {
    @Autowired(required = false)
    private DocumentService documentService;
    //6.查询附件信息
    @RequestMapping(value = "/queryDocument",method = RequestMethod.POST)
    @ApiOperation(value = "查询附件接口",notes = "传递想要查询附件id",httpMethod = "POST", response = R.class)
    @ApiImplicitParams({

            @ApiImplicitParam(name = "documentary_id",value = "跟单id",dataType = "Integer",paramType = "query",required = true)
    })
    @ApiResponses({
            @ApiResponse(code=200,message="请求成功"),
            @ApiResponse(code=400,message="坏请求"),
            @ApiResponse(code=404,message="找不到页面"),
            @ApiResponse(code=405,message="Method请求错误"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ResponseBody
    public R queryDocument(@RequestParam(name = "documentary_id",required = true) Integer documentary_id){

            R r=documentService.queryDocument(documentary_id);
        return r;
    }
    //7.删除附件
    @RequestMapping(value = "/deleteDocument",method = RequestMethod.POST)
    @ApiOperation(value = "删除附件",notes = "传递想要删除附件id",httpMethod = "POST", response = R.class)
    @ApiImplicitParams({

            @ApiImplicitParam(name = "document_id",value = "要删除附件id",dataType = "String",paramType = "query",required = true)
    })
    @ApiResponses({
            @ApiResponse(code=200,message="请求成功"),
            @ApiResponse(code=404,message="找不到页面"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ResponseBody
    public R deleteDocument(@RequestParam(name = "document_id",required = true) Integer document_id){
        R r = documentService.deleteDocument(document_id);
        return r;
    }

    //10.附件上传

    @RequestMapping(value = "/addDocument",method = RequestMethod.POST)
    @ApiOperation(value = "附件上传接口",notes = "上传文件",httpMethod = "POST", response = R.class)

    @ResponseBody
    public R addDocument(com.gxa.pojo.File uploadfile, HttpServletRequest request) throws IOException {
        R r=new R();
        if(uploadfile.getFileList().isEmpty()){
            r.setCode(500);
            r.setMsg("没有选中文件");

        }else{//正常上传
            String uploadPath = request.getServletContext().getRealPath("") + File.separator + "upload" + File.separator;
            File file = new File(uploadPath);
            Map<String ,List<com.gxa.pojo.File>> result= new HashMap<>();
            List<com.gxa.pojo.File> resultlist= new ArrayList<>();
            if(!file.exists()){
                file.mkdirs();
            }
            List<MultipartFile> list = uploadfile.getFileList();
            for (MultipartFile file1: list
                 ) {
                String fileName = file1.getOriginalFilename();
                File newFile = new File(uploadPath + fileName);
                System.out.println("newFile=" + newFile);
                System.out.println(file1.getContentType());
                System.out.println("文件名"+fileName);

                String size=("文件大小"+String.format("%.2f",(double)file1.getSize()/1024/1024));
                //上传
                FileCopyUtils.copy(file1.getBytes(),newFile);

                com.gxa.pojo.File f=new com.gxa.pojo.File();
                f.setFileUrl(File.separator + "upload" + File.separator+fileName);
                f.setFileName(fileName);
                f.setFilesize(size);
                resultlist.add(f);

            }
            result.put("fileList",resultlist);
            r.setData(result);
            r.setCode(200);
            r.setMsg("上传成功");

        }


        return r;
    }
    //7.附件入库
    @RequestMapping(value = "/saveDocument",method = RequestMethod.POST)
    @ApiOperation(value = "附件入库",notes = "附件入库",httpMethod = "POST", response = R.class)
    @ApiResponses({
            @ApiResponse(code=200,message="请求成功"),
            @ApiResponse(code=404,message="找不到页面"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ResponseBody
    public R saveDocument(@RequestBody @ApiParam(name = "document",value = "附件实体集合",required = true) List<Document> documentList){
       R r=new R();
       for(Document document:documentList){
           System.out.println(document);
           r = documentService.addDocument(document);
       }

        return r;
    }
//下载

    @RequestMapping(value="/downloadDocument",method=RequestMethod.GET)
    @ApiOperation(value = "文件下载",notes = "文件下载",httpMethod = "GET", response = R.class)
    @ApiResponses({
            @ApiResponse(code=200,message="请求成功"),
            @ApiResponse(code=404,message="找不到页面"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ResponseBody
    public void download(HttpServletRequest request, HttpServletResponse response,String document_name) throws IOException {
        //checkPay.apk为需要下载的文件
        //String filename = "checkPay.apk";   //我这里使用的是一个固定的文件，方法可以不用写filename参数
        //获取文件的绝对路径名称，upload为根目录下的一个文件夹，这个只能获取根目录文件夹的绝对路径
        String path = request.getSession().getServletContext().getRealPath("upload") + "\\" + document_name;
        System.out.println(path);


        //得到要下载的文件
        File file = new File(path);
        if (!file.exists()) {
            response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
            response.getWriter().print("<html><body><script type='text/javascript'>alert('您要下载的资源已被删除！');</script></body></html>");
            response.getWriter().close();
            System.out.println("您要下载的资源已被删除！！");
            return;
        }
        //转码，免得文件名中文乱码
            document_name = new String(document_name.getBytes("UTF-8"), "ISO8859-1");

            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + document_name);

            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            // 读取要下载的文件，保存到文件输入流
            FileInputStream in = new FileInputStream(path);
            // 创建输出流
            OutputStream out = response.getOutputStream();
            // 创建缓冲区
            byte buffer[] = new byte[1024]; // 缓冲区的大小设置是个迷  我也没搞明白
            int len = 0;
            //循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            //关闭文件输入流
            in.close();
            // 关闭输出流
            out.close();



    }

    @RequestMapping(value = "/queryDocumentByRepair",method = RequestMethod.POST)
    @ApiOperation(value = "查询附件接口",notes = "传递想要查询附件id",httpMethod = "POST", response = R.class)
    @ApiImplicitParams({

            @ApiImplicitParam(name = "repair_id",value = "工单查询附件id",dataType = "String",paramType = "query",required = true)
    })
    @ApiResponses({
            @ApiResponse(code=200,message="请求成功"),
            @ApiResponse(code=400,message="坏请求"),
            @ApiResponse(code=404,message="找不到页面"),
            @ApiResponse(code=405,message="Method请求错误"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ResponseBody
    public R queryDocumentByRepair(@RequestParam(name = "repair_id",required = true) Integer repair_id){

        R r=documentService.queryDocumentByRepair(repair_id);
        return r;
    }

}

